<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>执行记录 - 后台管理</title>
  <link rel="stylesheet" href="/static/base.css">
  <link rel="stylesheet" href="/static/components.css">
  <link rel="stylesheet" href="/static/pages.css">
  <link rel="stylesheet" href="/static/admin/admin.css">
</head>
<body>
  <div class="admin-layout">
    <!-- 顶部导航 -->
    <div class="admin-header">
      <h2>执行记录</h2>
      <div>
        <button class="btn" onclick="location.href='/'">返回前台</button>
        <button class="btn" onclick="logout()">退出</button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="admin-main">
      <!-- 左侧导航（公共组件注入） -->
      <div class="admin-sidebar"></div>

      <!-- 右侧内容区域 -->
      <div class="admin-content">
        <div class="content-page active">
          <h3>执行记录</h3>
          <p class="page-description">查看策略执行的详细记录和历史数据</p>

          <div class="content-card">
            <div style="display:flex; gap:12px; flex-wrap:wrap; align-items:center;">
              <input id="filter-date" type="date" class="form-control" style="width:200px;">
              <input id="filter-text" type="text" class="form-control" placeholder="按策略名/股票名过滤..." style="width:240px;">
              <button class="btn" onclick="reloadRecords()">筛选</button>
              <button class="btn" onclick="resetFilters()">清除</button>
            </div>
          </div>

          <div class="content-card">
            <h4>执行历史</h4>
            <div class="table-container performance-table-container">
              <table class="performance-table">
                <thead>
                  <tr>
                    <th>执行时间</th>
                    <th>执行日期</th>
                    <th>策略</th>
                    <th>结果数</th>
                    <th>缓存数</th>
                    <th>新执行</th>
                    <th>耗时(s)</th>
                    <th>动作</th>
                  </tr>
                </thead>
                <tbody id="records-body">
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="/static/admin/components/sidebar.js"></script>
  <script>
    // 策略英文->中文映射
    let STRATEGY_PAIRS = [];
    let STRATEGY_MAP = new Map();

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
      // 设置默认日期为今天
      const dateInput = document.getElementById('filter-date');
      if (dateInput) {
        dateInput.value = todayISO();
      }
      // 先加载策略对照表，再加载记录
      preloadStrategyMap().then(()=> reloadRecords());
      reloadRecords();
      injectAdminSidebar('/admin/execution-record');
    });
    async function preloadStrategyMap(){
      try{
        const resp = await fetch('/api/strategies');
        const json = await resp.json();
        if (json && json.success) {
          STRATEGY_PAIRS = json.data && json.data.strategies ? json.data.strategies : [];
          STRATEGY_MAP = new Map((STRATEGY_PAIRS||[]).filter(x=>Array.isArray(x) && x.length>=2));
        }
      }catch(e){ STRATEGY_PAIRS=[]; STRATEGY_MAP = new Map(); }
    }

    function strategyCn(name){
      if (!name) return '';
      return STRATEGY_MAP.get(name) || name;
    }


    // 执行记录相关函数
    function todayISO(){
      return new Date().toISOString().split('T')[0];
    }

    function formatYMD(d){
      if(!d) return '';
      if(typeof d === 'string'){
        const m = d.match(/\d{4}-\d{2}-\d{2}/);
        return m ? m[0] : d;
      }
      try{
        const dt = new Date(d);
        return isNaN(dt.getTime()) ? '' : dt.toISOString().split('T')[0];
      }catch(e){ return ''; }
    }

    async function reloadRecords(){
      try{
        const dateInput = document.getElementById('filter-date');
        if(!dateInput.value){ dateInput.value = todayISO(); }
        const date = dateInput.value;
        const q = document.getElementById('filter-text').value.trim();
        const resp = await fetch('/admin/api/strategy/records');
        const data = await resp.json();
        const body = document.getElementById('records-body');
        body.innerHTML = '';

        if(data && data.success){
          let rows = data.records || [];
          if(date) rows = rows.filter(r => (r.execution_date || '').startsWith(date));
          if(q){
            const low = q.toLowerCase();
            rows = rows.filter(r => (r.strategy || '').toLowerCase().includes(low));
          }
          rows.forEach(r => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
              <td><span class="execution-time">${r.execution_time || '-'}</span></td>
              <td><span class="execution-date">${formatYMD(r.execution_date)}</span></td>
              <td><span class="strategy-name">${strategyCn(r.strategy) || '-'}</span></td>
              <td><span class="result-count">${r.result_count || 0}</span></td>
              <td><span class="cache-count">${r.cache_count || 0}</span></td>
              <td><span class="new-count">${r.new_count || 0}</span></td>
              <td><span class="duration">${(r.duration || 0).toFixed(2)}</span></td>
              <td>
                <button class="btn btn-sm btn-primary" onclick="viewResults('${r.execution_date}', '${r.strategy}')">查看结果</button>
              </td>
            `;
            body.appendChild(tr);
          });
        }
      }catch(e){
        console.error('加载执行记录失败', e);
      }
    }

    function resetFilters(){
      document.getElementById('filter-date').value = '';
      document.getElementById('filter-text').value = '';
      reloadRecords();
    }

    function viewResults(date, strategy){
      // 跳转到结果分析页面并设置参数
      const params = new URLSearchParams();
      if(date) params.set('execution_date', formatYMD(date));
      if(strategy) params.set('strategy', strategy);
      window.location.href = '/admin/result-analysis?' + params.toString();
    }

         // 退出登录
     async function logout(){
       try{ 
         await fetch('/admin/logout', {method:'POST'}); 
         location.href='/admin/login'; 
       }catch(e){ 
         location.href='/admin/login'; 
       }
     }
  </script>

  <style>
    /* 执行记录页面专用样式 */
    
    /* 表格容器样式 */
    .performance-table-container {
      max-height: 60vh;
      overflow-y: auto;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      background: white;
    }

    /* 执行时间样式 */
    .execution-time {
      font-family: 'Courier New', monospace;
      font-size: 13px;
      color: #6c757d;
    }

    /* 执行日期样式 */
    .execution-date {
      font-weight: 600;
      color: #2c3e50;
      background: #f8f9fa;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 13px;
    }

    /* 策略名称样式 */
    .strategy-name {
      font-weight: 600;
      color: #2c3e50;
      font-size: 14px;
    }

    /* 数量统计样式 */
    .result-count,
    .cache-count,
    .new-count {
      font-family: 'Courier New', monospace;
      font-weight: 600;
      text-align: center;
      display: inline-block;
      min-width: 40px;
    }

    .result-count {
      color: #28a745;
    }

    .cache-count {
      color: #17a2b8;
    }

    .new-count {
      color: #ffc107;
    }

    /* 耗时样式 */
    .duration {
      font-family: 'Courier New', monospace;
      font-weight: 600;
      color: #6c757d;
      text-align: center;
    }

    /* 操作按钮样式 */
    .btn-sm {
      padding: 6px 12px;
      font-size: 12px;
      border-radius: 6px;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .performance-table-container {
        max-height: 50vh;
      }
      
      .execution-time,
      .execution-date {
        font-size: 12px;
      }
    }
  </style>
</body>
</html>
